<?php
class Sqlitecache {
	public function __construct() {
		$sPath = Base::getConf ( 'cache.path' );
		if (! is_dir ( dirname ( ROOT . '/' . $sPath ) )) {
			Base::$oBase->File_md ( dirname ( ROOT . '/' . $sPath ) );
		}
		$aInfo ['type'] = 'sqlite';
		$aInfo ['name'] = ROOT . '/' . $sPath;
		Base::$oBase->Db_connect ( $aInfo, 'cache' );
		$sSql = 'CREATE TABLE IF NOT EXISTS "cache" ("key" char(32) NOT NULL , "category" VARCHAR(20) NOT NULL , "value" TEXT, "expire" INTEGER, PRIMARY KEY ("key", "category"))';
		Base::$oBase->Db_exec ( $sSql, null, 'cache' );
	}
	
	/**
	 * 设置缓存
	 * $sKey缓存名
	 * $sValue缓存内容
	 * $sCategory缓存所属类型
	 *
	 * @param string $sKey
	 * @param string $sValue
	 * @param string $sCategory
	 */
	public function set($sKey, $sValue, $sCategory = '_DEFAULT_', $iTime = null) {
		$sKey = md5 ( $sKey );
		$sCategory = $sCategory == null ? '_DEFAULT_' : $sCategory;
		if ($iTime === 0) {
			$iExpire = 0;
		} else {
			$iExpire = $iTime ? time () + $iTime : Base::getConf ( 'cache.time' ) + time ();
		}
		$sValue = serialize ( $sValue );
		if (Base::$oBase->Db_get ( 'cache', array ('key' => $sKey, 'category' => $sCategory ), 'cache' )) {
			Base::$oBase->Db_update ( 'cache', array ('value' => $sValue, 'expire' => $iExpire ), array ('key' => $sKey, 'category' => $sCategory ), 'cache' );
		} else {
			Base::$oBase->Db_insert ( 'cache', array ('value' => $sValue, 'expire' => $iExpire, 'key' => $sKey, 'category' => $sCategory ), 'cache' );
		}
		return true;
	}
	
	/**
	 * 获取缓存
	 *
	 * @param string $sKey
	 * @param string $sCategory
	 */
	public function get($sKey, $sCategory = '_DEFAULT_') {
		$sMKey = md5 ( $sKey );
		$sCategory = $sCategory == null ? '_DEFAULT_' : $sCategory;
		$aInfo = Base::$oBase->Db_get ( 'cache', array ('key' => $sMKey, 'category' => $sCategory ), 'cache' );
		if ($aInfo === false) {
			return '__NOCACHE__';
		} elseif ($aInfo ['expire'] == 0 || $aInfo ['expire'] > time ()) {
			return @unserialize ( $aInfo ['value'] );
		} else {
			$this->del ( $sKey, $sCategory );
			return '__NOCACHE__';
		}
	}
	
	public function del($sKey, $sCategory = '_DEFAULT_') {
		$sKey = md5 ( $sKey );
		$sCategory = $sCategory == null ? '_DEFAULT_' : $sCategory;
		var_dump ( 'cache', array ('key' => $sKey, 'category' => $sCategory ), 'cache' );
		Base::$oBase->Db_del ( 'cache', array ('key' => $sKey, 'category' => $sCategory ), 'cache' );
		return true;
	}
	
	public function clear($sCategory = null) {
		if ($sCategory == null) {
			Base::$oBase->Db_exec ( 'DELETE FROM cache', null, 'cache' );
		} else {
			Base::$oBase->Db_exec ( 'DELETE FROM cache WHERE categroy = ?', $sCategory, 'cache' );
		}
		return true;
	}
	
	public function clearExpire() {
		$sSql = 'DELTE FROM cache WHERE expire > ? AND expire < ?';
		Base::$oBase->Db_exec ( $sSql, array (0, time () ), 'cache' );
	}
}